﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Business;
using BitPortal.Models;
using BitPortal.Utils;
using System.Web.Security;

namespace BitPortal.Admin.Customer.Module
{
    public partial class CustomerAddEdit : Controls.BaseAdminControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                BindCustomerGroup();
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        public void BindData(long customerID = 0)
        {
            if (customerID > 0)
            {
                BitPortal.Models.Customer customer = CustomerBLL.GetByID(customerID);
                if (customer != null)
                {
                    txtID.Text = customer.CustomerID.ToString();
                    txtNoteGroupID.Text = customer.NoteGroupID.ToString();
                    txtContactName.Text = customer.ContactName;
                    txtCompany.Text = customer.Company;
                    txtEmail.Text = customer.Email;
                    txtPhone.Text = customer.Phone;
                    txtFax.Text = customer.Fax;
                    txtWebsite.Text = customer.Website;
                    cbPriority.SelectedItem.Value = customer.Priority.ToString();

                    txtCountry.Text = customer.Country;
                    txtCity.Text = customer.City;
                    txtAddress1.Text = customer.Address;
                    txtAddress2.Text = customer.Address2;

                    txtDescription.Text = customer.Description;
                    if (customer.LastContactDate != null) txtLastContactDate.SelectedDate = (DateTime)customer.LastContactDate;
                    if (customer.LastRepliedDate != null) txtLastReplyDate.SelectedDate = (DateTime)customer.LastRepliedDate;
                    txtLastContactForm.Text = customer.LastContactForm;
                    txtLastReplyForm.Text = customer.LastRepliedForm;

                    cbGroup.Text = customer.GroupName;

                    ThumbImage.TextFieldURL.Text = customer.ThumbImage;

                    if (customer.UserID != null)
                    {
                        UserSelecter1.ComboboxUser.Text = Membership.GetUser(customer.UserID).UserName;
                    }

                    btnInsert.Hidden = true;
                    btnUpdate.Hidden = false;
                    Window1.Show();
                }
            }
            else
            {
                txtID.Text = txtNoteGroupID.Text = "0";
                txtContactName.Text = txtCompany.Text = txtCountry.Text = txtCity.Text = txtEmail.Text = txtPhone.Text = txtFax.Text
                    = txtAddress1.Text = txtAddress2.Text = txtWebsite.Text = txtDescription.Text = txtLastContactDate.Text
                    = txtLastContactForm.Text = txtLastReplyDate.Text = txtLastReplyForm.Text = ThumbImage.TextFieldURL.Text = "";

                btnInsert.Hidden = false;
                btnUpdate.Hidden = true;
                Window1.Show();
            }
        }

        protected void btnInsert_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("CustomerInsert");
                BitPortal.Models.Customer customer = new Models.Customer()
                {
                    ContactName = txtContactName.Text.Trim(),
                    Company = txtCompany.Text.Trim(),
                    Email = txtEmail.Text.Trim(),
                    Phone = txtPhone.Text.Trim(),
                    Fax = txtFax.Text.Trim(),
                    Website = txtWebsite.Text.Trim(),
                    Priority = cbPriority.SelectedItem.Value.ToInt32TryParse(),
                    GroupName = cbGroup.Text,
                    Country = txtCountry.Text.Trim(),
                    City = txtCity.Text.Trim(),
                    Address = txtAddress1.Text.Trim(),
                    Address2 = txtAddress2.Text.Trim(),
                    Description = txtDescription.Text,
                    LastContactDate = txtLastContactDate.SelectedDate > new DateTime(1990, 1, 1) ? (DateTime?)txtLastContactDate.SelectedDate : null,
                    LastContactForm = txtLastContactForm.Text,
                    LastRepliedDate = txtLastReplyDate.SelectedDate > new DateTime(1990, 1, 1) ? (DateTime?)txtLastReplyDate.SelectedDate : null,
                    LastRepliedForm = txtLastReplyForm.Text,
                    ThumbImage = ThumbImage.TextFieldURL.Text,
                    IsApproved = true,
                    IsDeleted = false,
                    LanguageCode = BitContext.Current.Lang.LanguageCode
                };
                //Logs
                customer.Logs.CreatingUser = customer.Logs.EditingUser = BitContext.Current.LoginUser;
                customer.Logs.DatetimeCreated = customer.Logs.DatetimeEdited = DateTime.Now;
                //User Reference
                if (!string.IsNullOrEmpty(UserSelecter1.ComboboxUser.Text))
                {
                    MembershipUser user = Membership.GetUser(UserSelecter1.ComboboxUser.Text);
                    if (user != null) customer.UserID = new Guid(user.ProviderUserKey.ToString());
                }
                if (customer.Insert() > 0)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Thêm thông tin khách hàng thành công!");
                    Window1.Hide();
                    ReloadTargetData();
                }
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
        }

        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                long Id = txtID.Text.ToInt64TryParse();
                Models.Customer customer = bitEnt.Customers.SingleOrDefault(ent => ent.CustomerID == Id);
                if (customer != null)
                {
                    customer.ContactName = txtContactName.Text.Trim();
                    customer.Company = txtCompany.Text.Trim();
                    customer.Email = txtEmail.Text.Trim();
                    customer.Phone = txtPhone.Text.Trim();
                    customer.Fax = txtFax.Text.Trim();
                    customer.Website = txtWebsite.Text.Trim();
                    customer.Priority = cbPriority.SelectedItem.Value.ToInt32TryParse();
                    customer.GroupName = cbGroup.Text;
                    customer.Country = txtCountry.Text.Trim();
                    customer.City = txtCity.Text.Trim();
                    customer.Address = txtAddress1.Text.Trim();
                    customer.Address2 = txtAddress2.Text.Trim();
                    customer.Description = txtDescription.Text;
                    customer.LastContactDate = txtLastContactDate.SelectedDate > new DateTime(1990, 1, 1) ? (DateTime?)txtLastContactDate.SelectedDate : null;
                    customer.LastContactForm = txtLastContactForm.Text;
                    customer.LastRepliedDate = txtLastReplyDate.SelectedDate > new DateTime(1990, 1, 1) ? (DateTime?)txtLastReplyDate.SelectedDate : null;
                    customer.LastRepliedForm = txtLastReplyForm.Text;
                    customer.ThumbImage = ThumbImage.TextFieldURL.Text;
                    //Logs
                    customer.Logs.EditingUser = BitContext.Current.LoginUser;
                    customer.Logs.DatetimeEdited = DateTime.Now;
                    //User Reference
                    if (!string.IsNullOrEmpty(UserSelecter1.ComboboxUser.Text))
                    {
                        MembershipUser user = Membership.GetUser(UserSelecter1.ComboboxUser.Text);
                        if (user != null) customer.UserID = new Guid(user.ProviderUserKey.ToString());
                    }
                    if (bitEnt.SaveChanges() > 0)
                    {
                        (this.Page as Controls.BaseAdminPage).ShowNotification("Cập nhật khách hàng thành công!");
                        Window1.Hide();
                        ReloadTargetData();
                    }
                }

            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }

        }

        protected void btnAddCustomer_Click(object sender, DirectEventArgs e)
        {
            wCustomer.AutoLoad.Url = "/Admin/Account/Admin/?Role=Customer";
            wCustomer.LoadContent();
            wCustomer.Show();
        }
        protected void btnNotes_Click(object sender, DirectEventArgs e)
        {
            wNote.AutoLoad.Url = "/Admin/Note/?NoteGroupID="+txtNoteGroupID.Text;
            wNote.LoadContent();
            wNote.Show();
        }
        protected void BindCustomerGroup()
        {
            ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
            var list = (from ent in bitEnt.Customers
                        where !string.IsNullOrEmpty(ent.GroupName)
                        orderby ent.GroupName ascending
                        select new { Group = ent.GroupName }).Distinct();
            Store11.DataSource = list;
            Store11.DataBind();
        }

    }
}